package com.zrj.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

/**
 * 网关配置
 *
 * @author zrj
 * @since 2022/10/7
 **/
@Configuration
public class GatewayConfig {

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        //@formatter:off
        return builder.routes()
                .route( "bin_route", r -> r.path( "/get" )
                        .uri( "http://httpbin.org" ) )
                .route( "news_route", r -> r.path( "/news" )
                        .uri( "http://news.baidu.com/guonei" ) )
                //trade route
                //.route( "trade_route", r -> r.path( "/trade/**" )
                //        .uri( "lb://cloud-marking-service" ) )
                //trade限流redisRateLimiter
                .route( "trade_route", r -> r.path( "/trade/get" )
                        .filters( f -> f.requestRateLimiter( c -> c.setRateLimiter( redisRateLimiter() ) ) )
                        .uri( "lb://cloud-marking-service" ) )
                .build();
        //@formatter:on
    }

    /**
     * int defaultReplenishRate：令牌桶每秒填充平均速率
     * int defaultBurstCapacity：令牌桶上线
     */
    @Bean
    RedisRateLimiter redisRateLimiter() {
        return new RedisRateLimiter( 1, 2 );
    }

    @Bean
    public KeyResolver pathKeyResolver() {
        return exchange -> Mono.just(
                exchange.getRequest().getPath().toString()
        );
    }
}
